<template>
  <div class="notifications-container">
    <el-card class="notification-card">
      <template #header>
        <div class="card-header">
          <h2>通知中心</h2>
          <div class="header-actions">
            <el-button type="primary" size="small" :disabled="selectedNotifications.length === 0" @click="markAsRead">
              标记为已读
            </el-button>
            <el-button type="danger" size="small" :disabled="selectedNotifications.length === 0" @click="deleteNotifications">
              删除
            </el-button>
          </div>
        </div>
        <div class="filter-bar">
          <el-radio-group v-model="readStatus" size="small" @change="handleReadStatusChange">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="unread">未读</el-radio-button>
            <el-radio-button label="read">已读</el-radio-button>
          </el-radio-group>
          <el-select v-model="notificationType" placeholder="通知类型" clearable @change="handleTypeChange">
            <el-option v-for="type in notificationTypes" :key="type.value" :label="type.label" :value="type.value" />
          </el-select>
        </div>
      </template>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>
      
      <div v-else-if="notifications.length === 0" class="empty-container">
        <el-empty description="暂无通知" />
      </div>
      
      <el-table 
        v-else
        :data="notifications" 
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="状态" width="60">
          <template #default="scope">
            <el-badge is-dot :hidden="scope.row.readStatus === 'read'" type="danger" />
            <span class="notification-status">
              {{ scope.row.readStatus === 'read' ? '已读' : '未读' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="通知类型" width="120">
          <template #default="scope">
            <el-tag :type="getNotificationTypeTag(scope.row.type)" size="small">
              {{ getNotificationTypeName(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" />
        <el-table-column label="内容" min-width="200" show-overflow-tooltip>
          <template #default="scope">
            <div class="notification-content">{{ scope.row.content }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="时间" width="180">
          <template #default="scope">
            {{ new Date(scope.row.createTime).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button 
              size="small" 
              @click="viewDetail(scope.row)"
            >
              查看
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              plain
              @click="deleteNotification(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 通知详情对话框 -->
    <el-dialog v-model="dialogVisible" title="通知详情" width="50%">
      <template v-if="currentNotification">
        <h3>{{ currentNotification.title }}</h3>
        <div class="notification-meta">
          <el-tag :type="getNotificationTypeTag(currentNotification.type)" size="small">
            {{ getNotificationTypeName(currentNotification.type) }}
          </el-tag>
          <span class="notification-time">
            {{ new Date(currentNotification.createTime).toLocaleString() }}
          </span>
        </div>
        <div class="notification-detail-content">
          {{ currentNotification.content }}
        </div>
        <div v-if="currentNotification.documentId" class="notification-actions">
          <el-button type="primary" @click="viewDocument(currentNotification.documentId)">
            查看文档
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

// 加载状态
const loading = ref(true)

// 分页状态
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 筛选状态
const readStatus = ref('all') // all, read, unread
const notificationType = ref('')
const notificationTypes = [
  { value: 'document_update', label: '文档更新' },
  { value: 'document_new', label: '新文档' },
  { value: 'system', label: '系统通知' }
]

// 数据
const notifications = ref([])
const selectedNotifications = ref([])

// 详情对话框
const dialogVisible = ref(false)
const currentNotification = ref(null)

// 初始化
onMounted(() => {
  fetchNotifications()
})

// 获取通知列表
async function fetchNotifications() {
  loading.value = true
  try {
    // 这里替换为实际的API调用
    // const response = await axios.get('/api/notifications', {
    //   params: {
    //     page: currentPage.value,
    //     size: pageSize.value,
    //     status: readStatus.value,
    //     type: notificationType.value
    //   }
    // })
    
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 500))
    
    notifications.value = Array.from({ length: 10 }, (_, i) => {
      const types = ['document_update', 'document_new', 'system']
      const type = types[Math.floor(Math.random() * types.length)]
      const readStatuses = ['read', 'unread']
      const status = readStatuses[Math.floor(Math.random() * readStatuses.length)]
      
      return {
        id: i + 1,
        title: `${type === 'document_update' ? '文档更新' : type === 'document_new' ? '新文档' : '系统通知'} ${i + 1}`,
        content: `这是一条${type === 'document_update' ? '文档更新' : type === 'document_new' ? '新文档' : '系统通知'}通知，内容详情请点击查看。`,
        type: type,
        readStatus: status,
        createTime: new Date().getTime() - Math.floor(Math.random() * 10000000),
        documentId: type !== 'system' ? Math.floor(Math.random() * 20) + 1 : null
      }
    })
    
    // 根据筛选条件过滤
    if (readStatus.value !== 'all') {
      notifications.value = notifications.value.filter(item => item.readStatus === readStatus.value)
    }
    
    if (notificationType.value) {
      notifications.value = notifications.value.filter(item => item.type === notificationType.value)
    }
    
    total.value = 30 // 模拟总数
  } catch (error) {
    console.error('Failed to fetch notifications:', error)
    ElMessage.error('获取通知列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 根据通知类型获取显示名称
function getNotificationTypeName(type) {
  switch (type) {
    case 'document_update':
      return '文档更新'
    case 'document_new':
      return '新文档'
    case 'system':
      return '系统通知'
    default:
      return '未知类型'
  }
}

// 根据通知类型获取标签类型
function getNotificationTypeTag(type) {
  switch (type) {
    case 'document_update':
      return 'success'
    case 'document_new':
      return 'primary'
    case 'system':
      return 'info'
    default:
      return 'info'
  }
}

// 查看通知详情
function viewDetail(notification) {
  currentNotification.value = notification
  dialogVisible.value = true
  
  if (notification.readStatus === 'unread') {
    // 标记为已读
    notification.readStatus = 'read'
    
    // 这里替换为实际的API调用
    // axios.put(`/api/notifications/${notification.id}/read`)
  }
}

// 查看相关文档
function viewDocument(documentId) {
  // 关闭对话框
  dialogVisible.value = false
  
  // 跳转到文档详情页
  ElMessage.info(`查看文档 ID: ${documentId}`)
}

// 表格选择变化
function handleSelectionChange(selection) {
  selectedNotifications.value = selection
}

// 批量标记为已读
async function markAsRead() {
  try {
    if (selectedNotifications.value.length === 0) return
    
    // 这里替换为实际的API调用
    // const ids = selectedNotifications.value.map(item => item.id)
    // await axios.put('/api/notifications/read', { ids })
    
    // 模拟标记为已读
    selectedNotifications.value.forEach(notification => {
      const index = notifications.value.findIndex(n => n.id === notification.id)
      if (index !== -1) {
        notifications.value[index].readStatus = 'read'
      }
    })
    
    ElMessage.success('标记为已读')
  } catch (error) {
    console.error('Failed to mark as read:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 批量删除通知
async function deleteNotifications() {
  try {
    if (selectedNotifications.value.length === 0) return
    
    await ElMessageBox.confirm(`确定要删除已选择的 ${selectedNotifications.value.length} 条通知吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里替换为实际的API调用
    // const ids = selectedNotifications.value.map(item => item.id)
    // await axios.delete('/api/notifications', { data: { ids } })
    
    // 模拟删除
    const deleteIds = selectedNotifications.value.map(item => item.id)
    notifications.value = notifications.value.filter(n => !deleteIds.includes(n.id))
    total.value -= selectedNotifications.value.length
    selectedNotifications.value = []
    
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete notifications:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

// 删除单条通知
async function deleteNotification(id) {
  try {
    await ElMessageBox.confirm('确定要删除这条通知吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里替换为实际的API调用
    // await axios.delete(`/api/notifications/${id}`)
    
    // 模拟删除
    notifications.value = notifications.value.filter(n => n.id !== id)
    total.value--
    
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete notification:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

// 筛选状态变化
function handleReadStatusChange() {
  currentPage.value = 1
  fetchNotifications()
}

// 通知类型变化
function handleTypeChange() {
  currentPage.value = 1
  fetchNotifications()
}

// 分页相关
function handleSizeChange(size) {
  pageSize.value = size
  fetchNotifications()
}

function handleCurrentChange(page) {
  currentPage.value = page
  fetchNotifications()
}
</script>

<style scoped>
.notifications-container {
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.notification-card {
  width: 100%;
  margin: 0 20px 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.card-header h2 {
  margin: 0;
}

.filter-bar {
  display: flex;
  gap: 15px;
  margin-top: 15px;
  padding: 0 20px;
}

.notification-content {
  color: #666;
  font-size: 13px;
}

.notification-status {
  font-size: 12px;
  margin-left: 5px;
}

.loading-container, 
.empty-container {
  padding: 40px 0;
  text-align: center;
  flex: 1;
}

.notification-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 10px 0 20px;
}

.notification-time {
  font-size: 12px;
  color: #666;
}

.notification-detail-content {
  padding: 20px 0;
  line-height: 1.6;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.notification-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.pagination-container {
  margin-top: 20px;
  padding-bottom: 20px;
  display: flex;
  justify-content: center;
}

.el-table {
  flex: 1;
}
</style> 